//
//  OrderHistoricalViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/7/31.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "OrderHistoricalViewController.h"
#import "JGPopView.h"
#import "TransactionCell.h"
#import "TranOrder.h"
#import "OrdeDealsViewController.h"
@interface OrderHistoricalViewController ()<selectIndexPathDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) NSMutableArray * dataArray; //全部数组
@property (nonatomic, strong) NSString * name;
@property (nonatomic, strong) NSString * market;
@property (nonatomic, assign) BOOL  isChooseMarket;
@property (nonatomic, strong) NSMutableArray * titlesArray; //币种数组
@property (nonatomic, strong) NSString * titlelable;
@property (nonatomic,strong) NoNetworkView * workView;
@property (nonatomic, assign) NSInteger         pages;
@end

@implementation OrderHistoricalViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidOpen) name:kWebSocketDidOpenNote object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(SRWebSocketDidReceiveMsg:) name:kWebSocketdidReceiveMessageNote object:nil];
    for (NSString * str in [AppDelegate shareAppdelegate].allCurrency) {
        NSArray *array = [str componentsSeparatedByString:@"_"];
        NSString * str = [NSString stringWithFormat:@"%@ / %@",array[0],array[1]];
        [self.titlesArray addObject:str];
    }
     _name = _titlesArray.firstObject;
    _market = [AppDelegate shareAppdelegate].allCurrency.firstObject;
    _titlelable = Localized(@"Asset_whole");
    [self getHistory:0 Maket:[AppDelegate shareAppdelegate].allCurrency.firstObject];
    [self.view addSubview:self.tableView];

}
// 获取历史list
- (void)getHistory:(NSInteger)side  Maket:(NSString *)maket
{
    
    NSArray * dataArray  = @[maket,@0,@0,@0,@100,@(side)];
    NSData *data = [EXUnit NSJSONSerializationWithmethod:@"order.history" parameter:dataArray id:1890];
    [[SocketRocketUtility instance] sendData:data];    // 发送数据
  
}
#pragma  mark -----懒加载
- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight - kStatusBarAndNavigationBarHeight - RealValue_W(88) - IPhoneBottom)style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorColor = CELLCOLOR;
        _tableView.delegate = self;
        _tableView.dataSource=self;
        _tableView.backgroundColor = TABLEVIEWLCOLOR;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[TransactionCell class] forCellReuseIdentifier:@"TransactionCell"];
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 0.000001)];
    }
    return _tableView;
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc]init];
    }
    return _dataArray;
}
- (NSMutableArray *)titlesArray
{
    if (!_titlesArray) {
        _titlesArray = [[NSMutableArray alloc]init];
    }
    return _titlesArray;
}
#pragma  mark -----tableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return RealValue_W(188);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return RealValue_W(108);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TransactionCell *cell = [_tableView dequeueReusableCellWithIdentifier:@"TransactionCell"];
    cell.hiustModle = self.dataArray[indexPath.row];
  
    [cell.revokebutton setTitle:Localized(@"Detailed") forState:(UIControlStateNormal)];
    WeakSelf
    [cell.revokebutton add_BtnClickHandler:^(NSInteger tag) {
        
        [weakSelf orderdealsWithindexPath:indexPath array:self.dataArray];
    }];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TranOrder *orderModle = self.dataArray[indexPath.row];
    OrdeDealsViewController * orderdealsVC = [[OrdeDealsViewController alloc] init];
    orderdealsVC.title = Localized(@"Business_details");
    NSArray *data = [orderModle.market componentsSeparatedByString:@"_"];
    orderdealsVC.makes = data;
    orderdealsVC.orderId = orderModle.id;
    if (orderModle.side.integerValue ==2)
    {
        orderdealsVC.isSell = NO;
    }else
    {
        orderdealsVC.isSell = YES;
    }
    [self.navigationController pushViewController:orderdealsVC animated:YES];
}
- (void)orderdealsWithindexPath:(NSIndexPath *)indexPath array:(NSMutableArray *)array
{
    TranOrder *orderModle = array[indexPath.row];
    OrdeDealsViewController * orderdealsVC = [[OrdeDealsViewController alloc] init];
    orderdealsVC.title = Localized(@"Business_details");
    NSArray *data = [orderModle.market componentsSeparatedByString:@"_"];
    orderdealsVC.makes = data;
    orderdealsVC.orderId = orderModle.id;
    if (orderModle.side.integerValue ==2)
    {
        orderdealsVC.isSell = NO;
    }else
    {
        orderdealsVC.isSell = YES;
    }
    [self.navigationController pushViewController:orderdealsVC animated:YES];
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, RealValue_W(108))];
    bottomView.backgroundColor = TABLEVIEWLCOLOR;
    
    UIButton * leftbutton = [[UIButton alloc] initWithFrame:CGRectMake(RealValue_W(25), RealValue_W(108)/2 - 15, 60, 30)];
    [leftbutton setTitle:_titlelable forState:(UIControlStateNormal)];
    [leftbutton setImage:[UIImage imageNamed:@"Drop-down"] forState:UIControlStateNormal];
    [leftbutton addTarget:self action:@selector(transactionButton:) forControlEvents:UIControlEventTouchUpInside];
    leftbutton.titleLabel.font = AutoFont(13);
    [leftbutton setTitleColor:maintitleLCOLOR forState:UIControlStateNormal];
    [leftbutton setTitleEdgeInsets:UIEdgeInsetsMake(0, -RealValue_W(30), 0, RealValue_W(30))];
    [leftbutton setImageEdgeInsets:UIEdgeInsetsMake(0, RealValue_W(80), 0, -RealValue_W(80))];
    leftbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;// 水平左对齐
    [bottomView addSubview:leftbutton];
    
    UIButton * rightbutton = [[UIButton alloc] initWithFrame:CGRectMake(UIScreenWidth - RealValue_W(25) -100, RealValue_W(108)/2 - 15, 100, 30)];
    [rightbutton setTitle:_name forState:(UIControlStateNormal)];
    [rightbutton setImage:[UIImage imageNamed:@"Drop-down"] forState:UIControlStateNormal];
    rightbutton.titleLabel.font = AutoFont(13);
    [rightbutton addTarget:self action:@selector(currencyButton:) forControlEvents:UIControlEventTouchUpInside];
    [rightbutton setTitleColor:maintitleLCOLOR forState:UIControlStateNormal];
    rightbutton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;// 水平左对齐
    [rightbutton centerHorizontallyImageAndTextWithPadding:-30];
    [bottomView addSubview:rightbutton];
    
    return bottomView;
}
- (void)popDataWithButton:(UIButton *)button  array:(NSArray *)dataArray PointX:(CGFloat)PointX Width:(CGFloat)Width
{
  
    CGPoint point = CGPointMake(PointX ,RealValue_W(108)/2 +10);
    CGFloat height;
    if (dataArray.count>8)
    {
        height = 8 * RealValue_W(80);
    }else
    {
        height =  dataArray.count * RealValue_W(80);
    }
    JGPopView *view2 = [[JGPopView alloc] initWithOrigin:point Width:Width Height:height Type:JGTypeOfUpRight Color:MAINBLACKCOLOR];
    view2.dataArray = dataArray;
    
    view2.row_height = 40;
    view2.delegate = self;
    [view2 popView];
    [self.view addSubview:view2];
}
//买入卖出
- (void)transactionButton:(UIButton *)button
{
    _isChooseMarket = NO;
    [self popDataWithButton:button array:@[Localized(@"transaction_all"),Localized(@"C2C_buy"),Localized(@"C2C_sell")]PointX:button.right - RealValue_W(30) Width:RealValue_W(140)];
}
- (void)currencyButton:(UIButton *)button
{
    _isChooseMarket = YES;
    CGFloat with;
    with =  RealValue_W(200);
    [self popDataWithButton:button array:_titlesArray PointX:button.right - RealValue_W(10)Width:with];
}
#pragma JGPopViewDelegate
- (void)selectIndexPathRow:(NSInteger)index{
    if (_isChooseMarket) {
        [self.dataArray removeAllObjects];
        _market = _titlesArray[index];
        _name = _titlesArray[index];
        _market = [AppDelegate shareAppdelegate].allCurrency[index];
        [self getHistory:0 Maket:_market];
   }else
   {
       switch (index) {
           case 0:
               _titlelable = Localized(@"transaction_all");
               [self getHistory:0 Maket:_market];
               break;
           case 1:
               _titlelable = Localized(@"C2C_buy");
               [self getHistory:2 Maket:_market];
               break;
           case 2:
                _titlelable = Localized(@"C2C_sell");
               [self getHistory:1 Maket:_market];
               break;
           default:
               break;
       }
       [self.dataArray removeAllObjects];
   }
}
- (void)placeholderViewWithFrame:(CGRect)frame NoNetwork:(BOOL)NoNetwork
{
    if (_dataArray.count == 0)
    {
        [_workView removeFromSuperview];
        _workView = [[NoNetworkView alloc] initWithFrame:frame NoNetwork:NoNetwork];
        if (NoNetwork) {
            _workView.buttonclickeBlock = ^(UIButton *button) { //重新加载
                
            };
        }
        [_tableView addSubview:_workView];
    }else
    {
        [_workView dissmiss];
    }
    
}
- (void)SRWebSocketDidOpen
{
    
}
- (void)SRWebSocketDidReceiveMsg:(NSNotification *)note {
    //收到服务端发送过来的消息
    NSString * message = note.object;
    if ([NSString isEmptyString:message]) {
        return;
    }
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *message1 = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves  error:nil];
    if ([message1[@"id"] isEqual:[NSNull null]]) {
        return;
    }
    if ([message1[@"id"] integerValue] ==1890)
    {
        if ([message1[@"result"] isEqual:[NSNull null]]) {
            return;
        }
        NSArray * data = message1[@"result"][@"records"];
        self.dataArray = [TranOrder mj_objectArrayWithKeyValuesArray:data];
        NSIndexSet *indexSet=[[NSIndexSet alloc]initWithIndex:0];
        [_tableView reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
        [self placeholderViewWithFrame:CGRectMake(0, RealValue_W(108), _tableView.width, _tableView.height-RealValue_W(108)) NoNetwork:NO];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
